﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Net;
using System.Threading;
namespace WindowsWeb
{
    public class ComputerInfo
    {
        private static ComputerInfo _Current;
        public static ComputerInfo Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new ComputerInfo();
                }
                return _Current;
            }
        }

        /// <summary>
        /// 获取外网IP，没有返回空字符串
        /// </summary>
        /// <returns></returns>
        public string netIPBack()
        {
            //Uri uri = new Uri("http://www.ip138.com/ip2city.asp");//查本机网络IP的网页
            Uri uri = new Uri("http://city.ip138.com/city.asp");//查本机网络IP的网页
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = 0;
            req.CookieContainer = new CookieContainer();
            req.GetRequestStream().Write(new byte[0], 0, 0);
            HttpWebResponse res = (HttpWebResponse)(req.GetResponse());
            StreamReader rs = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("GB18030"));
            string s = rs.ReadToEnd();
            rs.Close();
            req.Abort();
            res.Close();
            s = s.Substring(s.IndexOf('[') + 1, s.Length - s.LastIndexOf(']') - 11);      //自己灵活取出IP
            return s;
            //Match m = Regex.Match(s, @"IP：\[(?<IP>[0-9\.]*)\]");
            //if (m.Success) return m.Groups["IP"].Value;
            //string strnetIP = string.Empty;
            //return strnetIP;
        }

        public string netIP()
        {
            Uri uri = new Uri("http://iframe.ip138.com/ic.asp");
            WebRequest wr = WebRequest.Create(uri);
            Stream s = wr.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s, System.Text.Encoding.Default);
            string all = sr.ReadToEnd(); //读取网站的数据
            int i = all.IndexOf("[") + 1;
            string tempip = all.Substring(i, 15);
            string ip = tempip.Replace("]", "").Replace(" ", "");//找出ip
            sr.Close();
            s.Close();
            return ip;
        }

        /// <summary>
        /// 获取局域网IP
        /// </summary>
        /// <returns></returns>
        public string getIP()//注意与static 的区别
        {
            System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;//获取本机内网IP
            return addressList[0].ToString();
        }

        public string getComputerName()
        {
            return System.Net.Dns.GetHostName();
        }
    }
}
